import { login, getCreditScore } from '/services/user';
if (!my.canIUse('plugin') && !my.isIDE) {
  my.ap && my.ap.updateAlipayClient && my.ap.updateAlipayClient();
}

App({
  globalData: {
    // 全局数据
    name: 'alipay',
    apiUrl: '',
    bnUri: '',
    ossHost: "https://gbuy.oss-cn-shanghai.aliyuncs.com",
    userInfo: undefined,
    chooseAddressID: 0,
    arealist: [],
    managerId: 0,

    playforminfo: {
      // 模式 rental/mall
      mode: 'rental',
      customerServicePhone: '18581998150',
      lossRule: 'lossRule',
      rentRule: 'rentRule',
      startRentDay: 3,
      dayList: [7, 15, 30, 180, 365]
    }
  },
  async onLaunch(options) {
    console.info("App onLaunch")
    await this.silenceLogin()
    console.info("App SilenceLogin Done")
  },
  silenceLogin() {
    return new Promise(async (resolve) => {
      if (this.globalData.userInfo) {
        return resolve(this.globalData.userInfo)
      }

      if (this.silenceLogin._isPosting_) {
        this.silenceLogin._resolveList_.push(resolve)
        return false
      } else {
        this.silenceLogin._isPosting_ = true
        this.silenceLogin._resolveList_ = [resolve]
      }

      /* 静默登陆 登录失败不做处理 */
      const ret = await my.getAuthCode({
        // scopes: ['auth_user', 'auth_zhima'],
        scopes: 'auth_base'
      });

      if (!ret || (ret.authErrorScopes && Object.keys(ret.authErrorScopes).length)) {
        return my.showToast({
          type: 'fail',
          content: '登录异常',
          duration: 2000,
        })
      }

      // const { code, data } = await getCreditScore({ code: ret.authCode })

      const { code, data } = await login({ 'code': ret.authCode }, true)
      if (code === 0) {
        this.globalData.userInfo = data
      }

      this.silenceLogin._resolveList_.forEach(rec => rec(this.globalData.userInfo))
    })
  },
  onShow(options) {
    if (options.managerId) {
      this.globalData.managerId = options.managerId
    }
    // 从后台被 scheme 重新打开
    // options.query == {number:1}
  },
});
